//
//  PlayerView.swift
//  FM
//
//  Created by x on 2017/9/28.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit
import CoreMedia

protocol updateFMDetailsInfoDelegate:NSObjectProtocol {
    
    /// 显示当前播放FM的详情信息
    ///
    /// - Parameter model: 当前播放FM的数据模型
    func showCurrentFMDetailsInfo(model:HomeFM)
}

class PlayerView: UIView {
    
    /// 更换信息的代理
    weak var delegate:updateFMDetailsInfoDelegate?
    
    //当前播放的FM
    var model:HomeFM? {
        didSet {
            //1.设置当前正在播放的FM
            currentFM = model
        }
    }
    
    /// 当前组所有的FM
    var FMS:[HomeFM]?
    
    /// 当前正在播放的FM
    var currentFM:HomeFM? {
        didSet {
            //0.更新界面显示信息
            if delegate?.showCurrentFMDetailsInfo(model: currentFM!) != nil {
                delegate?.showCurrentFMDetailsInfo(model: currentFM!)
            }
            
            //1.赋值
            iconImage.sd_setImage(with: currentFM?.iconImageURL)
            
            //2设置播放按钮的状态(更换播放歌曲的时候)
            playerBtu.isSelected = false
            
            //2.1恢复头像的动画
            iconImage.layer.resumeAnimation()
            
            //3.添加动画
            removeAnimation()
            addAnimation()

            //4.开始播放当前远程音乐
            FMPlayerTools.shareInstance().playFM(url: (currentFM?.fmURL)!)
        }
    }
    
    ///管理时间进度的定时器
    var timer:Timer?
    
    /// 标记是否循环(默认是false 不循环)
    var isLoop:Bool = false
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //1.监听音频加载状态
        NotificationCenter.default.addObserver(self, selector: #selector(loadSuccess), name: NSNotification.Name.init(playItemLoadSuccess), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(loadFiled), name: NSNotification.Name.init(playItemLoadFiled), object: nil)
        
        //1.2监听音频播放完成的通知
        NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
        
        //2.初始化界面
        setupUI()
    }
    
    /// 时间字符串转换
    ///
    /// - Parameter time: <#time description#>
    /// - Returns: <#return value description#>
    func timeString(time:TimeInterval) -> String {
        let dMin = Int(time) / 60;
        let dSec = Int(time) % 60;
        
        //设置时间00::00 下面两种都可以
        //return String.init(NSString(format: "%02d:%02d",dMin,dSec))
        return String.init(format: "%02d:%02d", dMin,dSec)
    }
    
    /// 按钮点击事件
    ///
    /// - Parameter btu: <#btu description#>
    func btuClick(btu:UIButton) -> Void {
        switch btu.tag {
        case 1:
            guard FMS == nil else {
                
                //1.拿到当前FM的下标
                var currentIndex = FMS?.index(of: currentFM!)
                
                //2.取得将要播放的FM
                if currentIndex == 0 {
                    currentIndex = (FMS?.count)!-1
                }else {
                    currentIndex = currentIndex! - 1
                }
                
                //3取得将要播放的FM
                currentFM = FMS?[currentIndex!]
                
                return
            }
        case 2:
            btu.isSelected = !btu.isSelected
            if btu.isSelected {
                //代表暂停
                FMPlayerTools.shareInstance().pauseFM()
                iconImage.layer.pauseAnimation()
                removeTimer()
            }else {
                //代表播放
                FMPlayerTools.shareInstance().playerFM()
                iconImage.layer.resumeAnimation()
                addTimer()
            }
        case 3:
            guard FMS == nil else {
                
                //1.拿到当前FM的下标
                var currentIndex = FMS?.index(of: currentFM!)
    
                //2.取得将要播放的FM
                if currentIndex == FMS?.count {
                    currentIndex = 0
                }else {
                    currentIndex = currentIndex! + 1
                }
                
                //3取得将要播放的FM
                currentFM = FMS?[currentIndex!]
                
                return
            }

        default:
            break
        }
    }
    
    /// 循环按钮点击事件
    func loopBtuClick(btu:UIButton) -> Void {
        btu.isSelected = !btu.isSelected
        if btu.isSelected {
            loopLbale.text = "单曲播放"
        }else {
            loopLbale.text = "循环播放"
        }
        isLoop = btu.isSelected
    }
    
    /// 增加一个计时器
    func addTimer() -> Void {
        updateProgress()
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateProgress), userInfo: nil, repeats: true)
        //把定时器添加到RunLoop中防止滑动的时候定时器不执行
        RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes)
    }
    
    /// 删除定时器
    func removeTimer() -> Void {
        timer?.invalidate()
        timer = nil
    }
    
    /// 更新进度条进度
    func updateProgress() -> Void {
        
        //1.更新lable的显示时间
        currentTimeLable.text = timeString(time: FMPlayerTools.shareInstance().getCurrentPlayingTime())
        
        //2.更新进度条的进度
        progressSlide.value = Float(FMPlayerTools.shareInstance().getCurrentPlayingFMProgress())
    }
    
    /// 增加动画
    func addAnimation() -> Void {
        let baseAnimation = CABasicAnimation()
        //1.设置动画类型
        baseAnimation.keyPath = "transform.rotation"
        
        //2.设置动画终点至
        baseAnimation.toValue = Double.pi * 2
        
        //3.设置动画时间
        baseAnimation.duration = 30
        
        //4.设置动画次数
        baseAnimation.repeatCount = MAXFLOAT
        
        //5.添加动画
        iconImage.layer.add(baseAnimation, forKey: "imageRotation")
    }
    
    /// 移除动画
    func removeAnimation() -> Void {
        iconImage.layer.removeAnimation(forKey: "imageRotation")
    }
    
    /// 返回视图的高度
    ///
    /// - Returns: <#return value description#>
    func playerViewHeight() -> CGFloat {
        
        //1.重新布局拿到高度
        layoutIfNeeded()

        return playerBtu.frame.maxY + 10
    }
    
    /// 初始化
    func setupUI() -> Void {
        
        //1.添加子控件
        addSubview(iconImage)
        addSubview(progressSlide)
        addSubview(currentTimeLable)
        addSubview(previousBtu)
        addSubview(playerBtu)
        addSubview(nextBtu)
        addSubview(durationLable)
        addSubview(loopBtu)
        addSubview(loopLbale)
        
        //1.2给经度条添加手势
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapGR(tap:)))
        progressSlide.addGestureRecognizer(tap);
        
        //2.布局子控件
        let dic = ["iconImage":iconImage,
                   "progressSlide":progressSlide,
                   "currentTimeLable":currentTimeLable,
                   "previousBtu":previousBtu,
                   "playerBtu":playerBtu,
                   "nextBtu":nextBtu,
                   "durationLable":durationLable,
                   "loopBtu":loopBtu,
                   "loopLbale":loopLbale] as [String:Any]
        
        var cons:[NSLayoutConstraint] = [NSLayoutConstraint]()
        
        //FM头像
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[iconImage(120)]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[iconImage(120)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        cons.append(NSLayoutConstraint.init(item: iconImage, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0))
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-30-[progressSlide]-30-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[iconImage]-15-[progressSlide]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-30-[currentTimeLable]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[progressSlide]-10-[currentTimeLable(30)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)

        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[previousBtu(30)]-30-[playerBtu]", options: NSLayoutFormatOptions.alignAllTop, metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[previousBtu(30)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)

        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[playerBtu(30)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[progressSlide]-10-[playerBtu(30)]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: dic)

        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[playerBtu]-30-[nextBtu(30)]", options: NSLayoutFormatOptions.alignAllTop, metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[nextBtu(30)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[durationLable]-30-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[progressSlide]-10-[durationLable(30)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)

        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[iconImage]-0-[loopBtu(20)]", options: NSLayoutFormatOptions.alignAllBottom, metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[loopBtu(20)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[loopBtu]-[loopLbale]", options: NSLayoutFormatOptions.alignAllBottom, metrics: nil, views: dic)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[loopLbale]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        
        addConstraints(cons)
        
    }
    
        
    deinit {
        FMPlayerTools.shareInstance().pauseFM()
    }
    
    //MARK: -- 懒加载
    
    private lazy var iconImage:UIImageView = UIImageView.imageWith(radios: 60, imageName: "")
    
    fileprivate lazy var progressSlide:UISlider = {
        let silde = UISlider()
        silde.translatesAutoresizingMaskIntoConstraints = false
        silde.thumbTintColor = UIColor.white
        silde.minimumTrackTintColor = UIColor.RGBColor(r: 229, g: 98, b: 55)
        silde.maximumTrackTintColor = UIColor.RGBColor(r: 183, g: 181, b: 181)
        
        //給进度条添加事件
        silde.addTarget(self, action: #selector(startClick), for: UIControlEvents.touchDown)
        silde.addTarget(self, action: #selector(sildeValueChanged), for: UIControlEvents.valueChanged)
        silde.addTarget(self, action: #selector(endClick), for: UIControlEvents.touchUpInside)
        
        return silde
    }()
    
    /// 当前播放时间
    private lazy var currentTimeLable:UILabel  = UILabel.lableWith(title: "00:00", titleColor: UIColor.black, fontSize: 12)
    
    /// 上一个电台的按钮
    private lazy var previousBtu:UIButton = UIButton.buttonWith(image: "toolbar_prev_n_p", hightImage: "toolbar_prev_n_p", tag: 1, target: self, action: #selector(btuClick(btu:)))
    
    /// 播放按钮
    private lazy var playerBtu:UIButton = UIButton.buttonWith(image: "toolbar_pause_n_p", hightImage: "toolbar_play_n_p", tag: 2, target: self, action: #selector(btuClick(btu:)))
    
    /// 下一首按钮
    private lazy var nextBtu:UIButton = UIButton.buttonWith(image: "toolbar_next_n_p", hightImage: "toolbar_next_n_p", tag: 3, target: self, action: #selector(btuClick(btu:)))
    
    /// 该fm的总时间
    fileprivate lazy var durationLable:UILabel = UILabel.lableWith(title: "00:00", titleColor: UIColor.black, fontSize: 12)
    
    /// 循环按钮
    private lazy var loopBtu:UIButton = UIButton.buttonWith(image: "login_form_v_refresh", hightImage: "TTPlayerProgressBarThumb", tag: 0, target: self, action: #selector(loopBtuClick(btu:)))
    
    /// 循环播放标签
    private lazy var loopLbale:UILabel = UILabel.lableWith(title: "循环播放", titleColor: UIColor.black, fontSize: 16)
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK : -- 通知的一些方法
extension PlayerView {
    
    /// 音频加载成功
    func loadSuccess() -> Void {
        //1.添加定时器
        removeTimer()
        addTimer()
        
        //2.更新界面时间信息
        durationLable.text = timeString(time: FMPlayerTools.shareInstance().getCurrentPlayingDuration())
    }
    
    /// 音频加载失败
    func loadFiled() -> Void {
        SVProgressHUD.showError(withStatus: "加载失败,请检查网络重新加载!")
    }
    
    /// 音频播放完成
    func playerItemDidPlayToEndTime() -> Void {
        print(#function)
        //1.判断是否是循环状态
        if isLoop {
            FMPlayerTools.shareInstance().playFM(url: (currentFM?.fmURL)!)
        }else {
            guard FMS == nil else {
                
                //1.拿到当前FM的下标
                var currentIndex = FMS?.index(of: currentFM!)
                
                //2.取得将要播放的FM
                if currentIndex == FMS?.count {
                    currentIndex = 0
                }else {
                    currentIndex = currentIndex! + 1
                }
                
                //3取得将要播放的FM
                currentFM = FMS?[currentIndex!]
                
                return
            }
        }
    }
}

//MARK: -- silde的一些事件
extension PlayerView {
    
    /// 进度条按钮的手势点击事件
    ///
    /// - Parameter tap: <#tap description#>
    func tapGR(tap:UITapGestureRecognizer) -> Void {
        //1.获取当前点击的坐标
        let currentPoint = tap.location(in: progressSlide)
        
        //2.得到当前点击位置占总进度的比例
        let currentProgress = currentPoint.x / progressSlide.bounds.width
        
        //3.设置当前播放时间
        let currentTime = FMPlayerTools.shareInstance().getCurrentPlayingDuration()*Float64(currentProgress)
        FMPlayerTools.shareInstance().player.seek(to: CMTimeMakeWithSeconds(currentTime, Int32(NSEC_PER_SEC)), toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
        
        //4.刷新数据
        updateProgress()
        
    }
    
    /// 开始点击进度条
    func startClick() -> Void {
        removeTimer()
    }
    
    /// silde的值改变事件
    func sildeValueChanged() -> Void {
        //3.设置当前播放时间
        let currentTime = FMPlayerTools.shareInstance().getCurrentPlayingDuration()*Float64(progressSlide.value)
        FMPlayerTools.shareInstance().player.seek(to: CMTimeMakeWithSeconds(currentTime, Int32(NSEC_PER_SEC)), toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
    }
    
    /// 松开进度条的时候
    func endClick() -> Void {
        addTimer()
    }
}
